﻿namespace DcscDS.IdGenerator
{
    using System;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    public static class ServiceCollectionExtension
    {
        /// <summary>
        /// 添加 分布式ID 扩展
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddDcscIdGenerator(this IServiceCollection services, IConfiguration configuration)
        {
            ushort WorkerId;
            DateTime IdGeneratorBaseTime = configuration.GetValue<DateTime>("IdGenerator:BaseTime");//起始时间
            string IdGeneratorWorkerId = configuration.GetValue<string>("IdGenerator:WorkerId");//机器编号
            if (!string.IsNullOrEmpty(IdGeneratorWorkerId))
            {
                WorkerId = Convert.ToUInt16(IdGeneratorWorkerId);
            }
            else
            {
                WorkerId = 1;
            }

            IdGeneratorOptions options = new()
            {
                BaseTime = IdGeneratorBaseTime.ToUniversalTime(),
                WorkerId = WorkerId
            };

            //直接单例注入实例
            services.AddSingleton<IDcscIdGenerator>(new DcscIdGenerator(options));

            return services;
        }
    }
}
